package com.lxk.Filter;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import java.io.IOException;
import java.util.UUID;

/**
 * Created by Lxk on 2020/7/22.
 */
@Slf4j
public class TraceMdcFilter implements Filter {

    private static final String TRACE_ID = "traceId";

    /**
     * 统一进行log的traceId设置，便于查看log信息
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        insertMDC();
        try {
            filterChain.doFilter(servletRequest, servletResponse);
        } catch (Exception e) {
            log.error("catch exception e:",e);
        }
        cleanMDC();
    }

    private boolean insertMDC() {
        UUID uuid = UUID.randomUUID();
        String uniqueId = uuid.toString().replace("-", "");
        MDC.put(TRACE_ID, uniqueId);
        return true;
    }

    public void cleanMDC(){
        if (!StringUtils.isEmpty(MDC.get(TRACE_ID))) {
            MDC.remove(TRACE_ID);
        }
    }


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {

    }
}
